﻿@{
    ViewBag.Title = "订单列表";
    Layout = "~/Areas/Shared/_spEdit.cshtml";
   
}
<link href="@Url.Content("~/Scripts/Uploadify/3.1/uploadify.css")" rel="stylesheet"  type="text/css" />
<script src="@Url.Content("~/Scripts/Uploadify/3.1/swfobject.js")"   type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Uploadify/3.1/jquery.uploadify-3.1.min.js")"   type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Plugins/jquery-jtemplates.js")"   type="text/javascript"></script>

@using Kaiser.Extensions
@model Kaiser.Modules.Hiner.Models.Order.OrderBase
<style>
    .numberbox {
        width: 40px;
    }
</style>
<form method="post" id="Form1">
    <div class="ftitle">订单基础信息</div>

    <table>
        <tr>
            <td class="itemtxt" style="text-align: right">请选择供应商：
            </td>
            <td>
                <input id="selectSupplier" style="width: 200px" required="true" />
                @Html.HiddenFor(m => Model.OrderId)
                @Html.HiddenFor(m => Model.SupplierId)
            </td>
            <td class="itemtxt" style="text-align: right">订单日期：
            </td>
            <td>
                @if (Model.OrderDate.HasValue)
                {
 
                    @Html.TextBox(Html.PropertyNameFor(x => Model.OrderDate), Model.OrderDate.Value.ToString("yyyy-MM-dd"), new { @class = "easyui-datebox" })
                }
                else
                {
                    @Html.TextBoxFor(m => Model.OrderDate, new { @class = "easyui-datebox" })
                }

            </td>
        </tr>
        <tr>
            <td class="itemtxt" style="text-align: right">订单编号：
            </td>
            <td>
                @Html.TextBoxFor(m => Model.OrderNo, new { @Class = "easyui-validatebox", @required = "true" })
            </td>
            <td class="itemtxt" style="text-align: right">联系人：
            </td>
            <td>
                @Html.TextBoxFor(m => Model.OrderContacts, new { @Class = "easyui-validatebox", @required = "true" })
            </td>
        </tr>
        <tr>
            <td style="text-align: right">PI编号：
            </td>
            <td>
                @Html.TextBoxFor(m => Model.OrderPINo, new { @Class = "easyui-validatebox", @required = "true" })
            </td>
            <td style="text-align: right">上传PI：
            </td>
            <td>
                <div>
                    <div id="OrderPIFile">
                        <a href="#" class="upload" style="display: none">上传</a>
                    </div>
                    <div style="display: none">
                        @*<a href="#" class="replace">替换</a>*@
                        @* <a href="#" class="icon-download" ">下载</a>*@
                        @Html.Hidden("fileid", "")
                    </div>

                </div>
                @*@Html.TextBoxFor(m => Model.OrderPIFile, new { @Class = "easyui-validatebox", @required = "true" })*@
            </td>
        </tr>
    </table>

    <p></p>
    <div class="ftitle">调用（添加）产品基础数据</div>

    <div id="dg">
    </div>
    <p></p>
    <div class="ftitle">TERMS</div>

    <table>
        <tr>
            <td>1</td>
            <td>Delivery Date: 
                @if (Model.OrderDeliveryDate.HasValue)
                {
                    @Html.TextBox(Html.PropertyNameFor(x => Model.OrderDeliveryDate), Model.OrderDeliveryDate.Value.ToString("yyyy-MM-dd"), new { @class = "easyui-datebox" })
                }
                else
                {
                    @Html.TextBoxFor(m => Model.OrderDeliveryDate, new { @class = "easyui-datebox" })
                }

            </td>
        </tr>
        <tr>
            <td>2</td>
            <td>Payment:@Html.TextBoxFor(x => x.OrderPayMentD, new { @class = "numberbox" }) deposit,@Html.TextBoxFor(x => x.OrderPayMentB, new { @class = "numberbox" }) balance before shippement</td>
        </tr>
        <tr>
            <td>3</td>
            <td>Goods and Packing must be confirmed before Payment balanced.</td>
        </tr>
        <tr>
            <td>4</td>
            <td>Remark:@Html.TextBoxFor(x => x.OrderClause)</td>
        </tr>
    </table>

    @Html.HiddenFor(x => x.OrderPrice)

</form>

<script type="text/javascript">


    $.extend($.fn.datagrid.methods, {
        editCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });

    $.extend($.fn.datagrid.defaults.editors, {
        numberspinner: {
            init: function (container, options) {
                var input = $('<input type="text">').appendTo(container);
                return input.numberspinner(options);
            },
            destroy: function (target) {
                $(target).numberspinner('destroy');
            },
            getValue: function (target) {

                var obj = $('#dg');
                var productPrice = obj.datagrid('getRows')[editIndex]['ProductPrice'];
                var val = $(target).numberspinner('getValue');

                obj.datagrid('getRows')[editIndex]['ProductActualPrice'] = val * productPrice;


                return val;
            },
            setValue: function (target, value) {
                $(target).numberspinner('setValue', value);
            },
            resize: function (target, width) {
                $(target).numberspinner('resize', width);
            }
        }
    });

    function updateTotal() {

        var data = $('#dg').datagrid('getData');
    
        var quantity = 0;
        var totalPrice = 0;
        for (var i = 0; i < data.rows.length; i++) {
            var item = data.rows[i];
          
            if (item.Quantity) {
                quantity += parseInt(item.Quantity);
                totalPrice += parseInt(item.ProductActualPrice);
            }  
        }
        $(".f").remove();
        for (var i = 0; i < data.rows.length; i++) {
            var item = data.rows[i];
            if (item.Quantity) {

                $.each(item, function (name, value) {
                    // alert('<input type="hidden" class="f" name="OrderDetailList[' + i + '].' + name + '" value="' + (value == null ? '' : value) + '" />')
                    var hidden = $('<input type="hidden" class="f" name="OrderDetailList[' + i + '].' + name + '" value="' + (value == null ? '' : value) + '" />').appendTo("#Form1");
                });
            }
        }


        $("#OrderPrice").val(totalPrice);
     
        $('#dg').datagrid('reloadFooter', [
            { Quantity: quantity, ProductActualPrice: totalPrice, ProductPrice: 'Total' }
        ]);
    }

    $(document).ready(function () {
        $(".numberbox").numberspinner({ min: 1, max: 90, precision: 0, required: true });

        var g = $('#selectSupplier').combobox({
            panelWidth: 500,
            url: '@Url.Action("GetSupplierList", "SupplierManage", new { area = "Hiner" })',
            valueField: 'SupplierId',
            textField: 'SupplierName',
            mode: 'remote',
            multiple: false,
            onLoadSuccess:function (){},
            onSelect: function () {

                $("#SupplierId").val($('#selectSupplier').combobox('getValue'));


            },
            panelHeight: 'auto'
        });

        g.combobox("setValue", $("#SupplierId").val());
        var dgData = '@(new HtmlString(Model.OrderDetailList.ToJson()))' ;
        dgData = $.parseJSON(dgData);
        $('#dg').datagrid({

            singleSelect: true,
            showFooter: true,
            onLoadSuccess:function() {
                updateTotal();
            },
            columns: [[
                {
                    field: 'ProductId',
                    title: 'Item',
                    width: 200,
                    sortable: true,
                    formatter: function (value, row) {
                        return row.ProductName;
                    },
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'ProductId',
                            textField: 'ProductName',
                            url: '@Url.Action("GetProductList", "OrderManage", new { area = "Hiner" })',
                            onSelect: function (e) {
                                // alert(editIndex)
                                var obj = $('#dg');

                                if (e.Quantity == undefined) {
                                    e.Quantity = 1;
                                }

                                obj.datagrid('getRows')[editIndex] = e;
                                var quantity = obj.datagrid('getRows')[editIndex]['Quantity'] = 1;
                                obj.datagrid('getRows')[editIndex]['ProductActualPrice'] = quantity * e.ProductPrice;
                            },
                            required: true
                        }
                    }
                },
                {
                    field: 'ProductHDECode',
                    title: 'HDE Code',
                    width: 120,
                    sortable: true
                },
                {
                    field: 'ProductHinerCode',
                    title: 'HINER Code',
                    width: 120,
                    sortable: true
                },
                { field: 'ProductOERef', title: 'OE Ref.', width: 120, sortable: false },
                { field: 'ProductPrice', title: 'Price', width: 40, sortable: true },
                { field: 'Quantity', title: 'Qty', width: 80, editor: 'numberspinner' },
                { field: 'ProductActualPrice', title: 'Sum', width: 50 }
            ]],
            data: dgData,
            toolbar: [{
                text: '添加',
                iconCls: 'icon-add',
                handler: append
            }, '-', {
                text: '移除',
                iconCls: 'icon-remove',
                handler: removeit
            }],
            onClickRow: function () { updateTotal(); },
            onClickCell: onClickCell
        });

        // update footer rows with new data
        $('#dg').datagrid('reloadFooter', [
            { Quantity: @Model.OrderDetailList.Sum(x => x.Quantity), ProductActualPrice: @Model.OrderDetailList.Sum(x => x.ProductActualPrice), ProductPrice: 'Total' }
        ]);
      
        if (dgData.length == 0) {
            append();
            append();
            append();
            append();
        }
        //  append();
        
        $(".upload").each(function () {
          
            var o = $(this);
            var oid = o.attr("id");
            var attach = $("<div id='uplodeFile'></div>");
            o.after(attach);
            attach.uploadify({
                'formData': { "ObjectID": $("#OrderId").val(), "ObjectModule": "HinnerOrder" },
                'swf': '@Url.Content("~/Scripts/Uploadify/3.1/uploadify.swf")',
                'uploader': '@Url.Action("UploadFiles", "ProductManage", new { area = "Hiner" })',
                @*'buttonImage': '@Url.Content("~/Themes/images/Snap1.jpg")',*@
                height:40,
                'queueID': 'some_file_queue',
                'buttonCursor': 'arrow',
                "buttonText": "点我上传",
                onInit: function (instance) {
                    var obj = $("#" + instance.settings.id);

                    if (o.val() != '') {
                        obj.find(".uploadify-button").hide();
                        obj.find("img").remove();
                        obj.append('<img width=120 height=88  style="border: 1px solid #95b8e7" src="' + o.val() + '" />');

                    }

                },
                onUploadSuccess: function (a, b) {
                    var result = $.parseJSON(b);
                    if (result.msg != "" && result.msg != undefined) {
                        alert(result.msg);
                    } else {
                        var obj = $(this.wrapper[0]);
                        $("#OrderPIFile").next().show();
                       
                        var html ="<a href='#' class='addLink' onclick='downloadClick("+result.Data.ID+")'>"+result.Data.FileName+"</a>";
                        $(".addLink").remove();
                        $("#OrderPIFile").next().append(html);
                        //obj.find(".uploadify-button").hide();
                        //obj.find("img").remove();
                        //obj.append('<img width=120 height=88  style="border: 1px solid #95b8e7" src="' + result.Data.FilePath + '" />');
                        //o.val(result.Data.FilePath);
                        // var o = $(this.wrapper[0], "img").attr('src', result.Data.FilePath);
                        //   $("#fileToUpload222-button").html("background-image", "url('" + result.Data.FilePath + "')").before("<img width=80 height=80 src='" + result.Data.FilePath + "' />");

                    }
                }
            })
        })
    });

</script>

<script type="text/javascript">
    var editIndex = undefined;
    function endEditing() {
        if (editIndex == undefined) {
            return true;
        }
        if ($('#dg').datagrid('validateRow', editIndex)) {
            $('#dg').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }
    function onClickRow(index) {
        if (editIndex != index) {
            if (endEditing()) {
                $('#dg').datagrid('selectRow', index)
                    .datagrid('beginEdit', index);
                editIndex = index;
            } else {
                $('#dg').datagrid('selectRow', editIndex);
            }
        }
    }

    function onClickCell(index, field) {
        if (endEditing()) {
            $('#dg').datagrid('selectRow', index)
                .datagrid('editCell', { index: index, field: field });
            editIndex = index;
        }
    }

    function downloadClick(id)
    {
        window.location.href = '@Url.Action("ViewFile", "ProductManage", new { area = "Hiner" })?FileID='+id;
    }
    function append() {
        if (endEditing()) {
            $('#dg').datagrid('appendRow', { ProductName: '' });
            editIndex = $('#dg').datagrid('getRows').length - 1;
            $('#dg').datagrid('selectRow', editIndex)
                .datagrid('editCell', { index: editIndex, field: 'ProductName' });
        }
    }
    function removeit() {
        if (editIndex == undefined) {
            return;
        }
        $('#dg').datagrid('cancelEdit', editIndex)
            .datagrid('deleteRow', editIndex);
        editIndex = undefined;
        updateTotal();
    }

    function reject() {
        $('#dg').datagrid('rejectChanges');
        editIndex = undefined;
    }
    function getChanges() {
        var rows = $('#dg').datagrid('getChanges');
        alert(rows.length + ' rows are changed!');
    }
</script>
